const app = getApp();
const api = require('../../utils/api');
const util = require('../../utils/util');

var animation = {};

Page({
    data: {
        isPreview: false,
        fromShop: '', //来源店铺

        id: '', //商品id
        shopId: '',
        shopDetail: '',
        shopcartId: '', //商品对应的购物车id

        productDetail: '', //商品详情
        productDesc: '', //商品描述
        productQuantity: 1, //商品显示数量
        originalQuantity: 0, //商品在购物车中原来的数量

        productQuantityAnimation: {}, //商品详情弹窗的动画效果
        showProductQuantity: false, //选择商品数量弹窗
        isShowLayer: false, //弹窗遮罩层

        inviteCode: '', //邀请人的邀请码
    },
    onLoad(options) {
        console.log(options)
        if(options.scene) {
            let scene = options.scene;
            let arr = scene.split('%26');
            let data1 = arr[0].split('%3D');
            let data2 = arr[1].split('%3D');
            this.setData({
                id: data1[1],
                shopId: data2[1],
            });
        } else {
            this.setData({
                id: options.id,
                shopId: parseInt(options.shopId),
                fromShop: options.from ? options.from : '',
                inviteCode: options.inviteCode ? options.inviteCode : '',
            });
        }

        this.getDetail();
        this.getShopcartData();

        if(this.data.shopId) {
            this.getStoreInfo();
        }

        //设置微信分享功能：可分享小程序和分享朋友圈
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },
    onShow() {
        // 防止图片预览刷新页面
        if(!this.data.isPreview) {
            //初始化动画
            animation = wx.createAnimation({
                duration: 500,
                timingFunction: 'ease-out',
            });
        }
    },

    getDetail() { //获取商品详情
        api.post(`/index/product/detail?saleId=${this.data.id}`)
            .then(res => {
                let item = res;
                item.sku.price = item.sku.price.toFixed(2);
                let content = util.formatRichText(res.productDesc);
                this.setData({
                    productDetail: item,
                    productDesc: content,
                });

                if(this.data.shopId == 0 && this.data.fromShop == '' && this.data.productDetail.shopId !== 0) {
                    this.getStoreInfo(this.data.productDetail.shopId);
                }
            })
    },
    getStoreInfo(id = '') { //获取店铺信息
        let shopId = id ? id : this.data.shopId;
        api.post('/shop/detail?shopId=' + shopId)
            .then(res => {
                this.setData({
                    shopDetail: res
                });
            })
    },
    gotoStore() { //跳转店铺
        wx.navigateTo({
            url: '/pages/storeCategory/storeCategory?id=' + this.data.shopDetail.id,
        });
    },
    
    getShopcartData() { //获取购物车数据
        api.post('/order/cart/list')
            .then(res => {
                let list = res;
                list.forEach(item => {
                    item.detailList.forEach(pro => {
                        if(pro.productSkuSaleId == this.data.id) {
                            this.setData({
                                shopcartId: pro.id,
                                originalQuantity: pro.quantity,
                            });
                        }
                    })
                });
            })
    },
    previewImage(e) { //查看商品大图
        this.setData({
            isPreview: true, //防止页面刷新
        });
        let current = e.currentTarget.dataset.item;
        let url = this.data.productDetail.carouselImageList;
        wx.previewImage({
            current: current, //当前显示图片的http链接
            urls: url, // 需要预览的图片http链接列表
        });
    },

    openQuantity() { //打开选择数量弹窗
        animation.bottom('0').step();
        this.setData({
            productQuantityAnimation: animation.export(),
            showProductQuantity: true,
            isShowLayer: true
        });
    },
    closeQuantity() { //关闭选择数量弹窗
        animation.bottom('-100%').step();
        this.setData({
            productQuantityAnimation: animation.export(),
            showProductQuantity: false,
            isShowLayer: false,
        });
    },

    //商品操作
    quantityPlus() { //数量加
        let number = this.data.productQuantity;
        if(number == this.data.productDetail.limitQuantity) {
            wx.showToast({
                title: `该商品限购${this.data.productDetail.limitQuantity}件！`,
                icon: 'none'
            });
            return;
        }
        this.setData({
            productQuantity: number + 1,
        });
    },
    quantityMinus() { //数量减
        let number = this.data.productQuantity;
        if(number <= 1) {
            return;
        }
        this.setData({
            productQuantity: number - 1,
        });
    },
    addShopcart() { //加入购物车按钮
        if((this.data.originalQuantity + this.data.productQuantity) > this.data.productDetail.limitQuantity) {
            wx.showToast({
                title: `购物车已添加过商品，该商品限购${this.data.productDetail.limitQuantity}件！`,
                icon: 'none'
            });
        } else if(this.data.originalQuantity == 0 && this.data.productQuantity) {
            //第一次加购物车
            this.addShopcartSubmit();
        } else {
            //已加过购物车，去修改购物车数量
            this.dealShopcartQuantity(this.data.productQuantity);
        }
    },
    addShopcartSubmit() { //提交加入购物车
        api.post('/order/cart/add', {skuSaleId: this.data.id})
            .then(res => {
                this.setData({
                    originalQuantity: this.data.productQuantity,
                    shopcartId: res
                });
                if(this.data.productQuantity > 1) { //添加数量大于1，需进行下一步操作
                    this.dealShopcartQuantity(this.data.productQuantity-1);
                } else {
                    wx.showToast({
                        title: '添加购物车成功',
                        icon: 'success'
                    });
                    this.closeQuantity();
                    app.globalData.isRefreshShopcart = true;
                }
            })
    },
    dealShopcartQuantity(quantity) { //修改购物车数量
        api.post(`/order/cart/quantity?id=${this.data.shopcartId}&diffQuantity=${quantity}`)
            .then(() => {
                this.setData({
                    originalQuantity: this.data.productQuantity
                });
                wx.showToast({
                    title: '添加购物车成功',
                    icon: 'success'
                });
                this.closeQuantity();
                app.globalData.isRefreshShopcart = true;
            })
    },

    buyImmediately() { //立即购买
        if(app.globalData.userInfo.phone == '') {
            wx.showModal({
                title: '温馨提示',
                content: `请先完成会员注册！`,
                success: res => {
                    if(res.confirm) {
                        wx.navigateTo({
                            url: '/pages/login/login?dir=1',
                        });
                    }
                }
            });
            return;
        }

        let list = [];
        list.push({
            productSkuSaleId: this.data.id,
            productSkuSaleImage: this.data.productDetail.sku.skuThumbImage,
            productName: this.data.productDetail.productName,
            productSkuSaleName: this.data.productDetail.sku.skuName,
            price: this.data.productDetail.sku.price,
            memberPrice: this.data.productDetail.sku.memberPrice,
            couponAmount: this.data.productDetail.sku.couponAmount,
            rechargePrice: this.data.productDetail.sku.rechargePrice,
            quantity: this.data.productQuantity,
        });
        app.globalData.shopcartCacheList = list; //缓存购买列表
        
        //跳转确认订单页面
        let url = `/pages/orderConfirm/orderConfirm?inviteCode=${this.data.inviteCode}`;
        if(this.data.fromShop && parseInt(this.data.fromShop) === parseInt(this.data.shopId)) {
            url = url + `&shopId=${this.data.fromShop}&dir=0`;
        } else if(this.data.fromShop) {
            url = url + `&shopId=${this.data.fromShop}&dir=1`;
        } else if(this.data.productDetail.shopId !== 0) {
            url = url + `&shopId=${this.data.productDetail.shopId}&dir=0`;
        } else {
            url = url + `&shopId=${this.data.shopId}&dir=1`
        }
        
        wx.navigateTo({
            url: url,
        });
    },
    onShareAppMessage() {
        let path = `pages/productDetail/productDetail?id=${this.data.id}&shopId=0&inviteCode=${app.globalData.userInfo.invitationCode}`;
        return {
            title: this.data.productDetail.productName,
            desc: this.data.productDetail.productName,
            path: path, // 路径，传递参数到指定页面
        }
    }
})